﻿#include "mqtt.h"
#include <ArduinoJson.h>

char buff[50];
int car_speed=10;

WiFiClient espClient;
PubSubClient client(espClient);

// MQTT消息回调函数，该函数会在PubSubClient对象的loop方法中被调用
// void mqtt_callback(char *topic, byte *payload, unsigned int length)
// {
//     Serial.printf("Message arrived in topic %s, length %d\n", topic, length);
//     Serial.print("Message:");
//     for (int i = 0; i < length; i++)
//     {
//         Serial.print((char)payload[i]);
//     }
//     is_transfer_mqtt = 1;


//     // StaticJsonDocument<200> jsonBuffer;   //声明一个JsonDocument对象，长度200

//     // // 添加对象节点
//     // jsonBuffer["key1"] = 123;          // 整数
//     // jsonBuffer["key2"] = 123.123;      // 浮点数
//     // jsonBuffer["key3"] = "string";     // 字符串

//     // // 添加数组对象
//     // JsonArray array1 = jsonBuffer.createNestedArray("array");// 添加一个 "array" 数组
//     // array1.add(1);    // 往数组里面添加值
//     // array1.add(1.2);  // 往数组里面添加值
//     // array1.add(-10);  // 往数组里面添加值

//     // // 对象嵌套
//     // JsonObject root = jsonBuffer.createNestedObject("key4"); //添加一个对象节点
//     // root["key1"] = "hello";

//     // String output;
//     // serializeJson(jsonBuffer, output);  // 序列化JSON数据并导出字符串

//     // Serial.println(output);             // 串口打印最后输出的字符串

//     Serial.println("\n----------------END----------------");
// }

void init_wifi()
{
    //等待串口准备
    delay(100);
    //启动WIFI连接
    Serial.println("");
    Serial.print("Connection WIFI.");
    WiFi.begin();
    //检查连接状态
    int count = 0;
    while (WiFi.status() != WL_CONNECTED)
    {
        delay(1000);
        Serial.print(".");
        count++;
        //连接超次数
        if (count > 10)
        {
        Serial.println("WIFI Wait for Smartconfig");
        //设置为Station模式
        WiFi.mode(WIFI_STA);
        //开始智能配网
        WiFi.beginSmartConfig();
        while (1)
        {
            //智能配网成功
            if (WiFi.smartConfigDone())
            {
                WiFi.setAutoConnect(true);  // 设置自动连接
                count = 0;
                //返回再次连接
                break;
            }
        }
        }
    }

    //连接成功,打印WIFI信息
    Serial.println("");
    Serial.println("WIFI SmartConfig Success");
    Serial.printf("SSID:%s", WiFi.SSID().c_str());
    Serial.printf(", PSW:%s\r\n", WiFi.psk().c_str());
    Serial.print("LocalIP:");
    Serial.print(WiFi.localIP());
    Serial.print(" ,GateIP:");
    Serial.println(WiFi.gatewayIP());

    client.setServer(mqtt_broker, mqtt_port);
    while (!client.connected()) {
        String client_id = "esp32-client-";
        client_id += String(WiFi.macAddress());
        Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
            Serial.println("Public emqx mqtt broker connected");
        } else {
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    // publish and subscribe
    client.publish(topic_publish, "mqtt ready.");
    client.subscribe(topic_subscribe);
    client.setCallback(mqtt_callback);
}

void handleMqtt()
{
    // sprintf(buff, "the speed is %d m/s.", car_speed++);
    // String string_to_send = buff;


    // uint16_t string_length = string_to_send.length();

    // char output_value_char[string_length];
    // string_to_send.toCharArray(output_value_char, string_length);

    // for (uint8_t i = 0; i < string_length; i++)
    // {
    //     Serial.print(output_value_char[i]);
    // }
    // Serial.println();

    client.loop();
    // client.publish(topic, output_value_char);
    //delay(1000);
    // is_transfer_mqtt = 1;
}

void sendMessage(char *message)
{
   client.publish(topic_publish, message); 
}